<?php

namespace app\common\business;

use app\common\model\mysql\Goods as GoodsModel;
use app\common\model\mysql\Category as CategoryModel;
use app\common\business\GoodsSku as GoodsSkuBis;
use app\common\business\SpecsValue as SpecsValueBis;
use think\facade\Cache;

/**
 * Class Goods
 * @package app\common\business
 */
class Goods extends BusBase {
    public $model = NULL;

    public function __construct() {
        $this->model = new GoodsModel();
    }

    /**
     * 新增商品逻辑
     * @param $data
     * @return array|bool|int|mixed
     */
    public function insertData($data) {
        // 开启事务
        $this->model->startTrans();
        try {
            // 1.插入商品基础表
            $goodsId = $this->add($data);
            if (!$goodsId) {
                return $goodsId;
            }

            // 2.插入商品sku表
            if ($data['goods_specs_type'] == 1) { //统一规格
                $goodsSkuData = [
                    'goods_id' => $goodsId,
                ];
                // TODO
            } elseif ($data['goods_specs_type'] == 2) { //多规格
                $goodsSkuBisObj = new GoodsSkuBis();
                $data['goods_id'] = $goodsId;
                $res = $goodsSkuBisObj->saveAll($data);
                if (!empty($res)) {
                    // 总库存
                    $stock = array_sum(array_column($res, 'stock'));
                    $goodsUpdateData = [
                        'price'      => $res[0]['price'],
                        'cost_price' => $res[0]['cost_price'],
                        'stock'      => $stock,
                        'sku_id'     => $res[0]['id'],
                    ];
                    // 3.更新商品基础表总库存、默认展示商品数据
                    $goodsRes = $this->model->updateById($goodsId, $goodsUpdateData);
                    if (!$goodsRes) {
                        throw  new \think\Exception('insertData:goods主表更新失败');
                    }
                } else {
                    throw new \think\Exception('sku表新增失败');
                }
            }
            // 事务提交
            $this->model->commit();
        } catch (\think\Exception $e) {
            // TODO 失败处理
            debugLog($e->getMessage(), 'goods.log');
            // 事务回滚
            $this->model->rollback();
            return false;
        }
        return true;
    }

    /**
     * 获取分页列表的数据
     * @param $data
     * @param int $num
     * @return array
     */
    public function getLists($data, $num = 5) {
        $likeKeys = [];
        if (!empty($data)) {
            $likeKeys = array_keys($data);
        }
        try {
            $list = $this->model->getLists($likeKeys, $data, $num);
            $result = $list->toArray();
        } catch (\Exception $e) {
            $result = \app\common\lib\Arr::getPaginateDefaultData($num);
        }
        return $result;
    }

    /**
     * 商城首页推荐大图
     * @return array
     */
    public function getRotationChart() {
        $data = [
            'is_index_recommend' => 1,
        ];
        $field = 'sku_id as id, title, big_image as image';

        try {
            $result = $this->model->getNormalGoodsByCondition($data, $field, 5);
        } catch (\Exception $e) {
            return [];
        }
        return $result->toArray();
    }

    /**
     * 获取商品分类下列表
     * @param $category
     * @return array
     * @throws \think\db\exception\DbException
     */
    public function categoryGoodsRecommend($category = []) {
        // 获取前3个
        if (!$category) {
            $category = (new CategoryModel())->getLimitCategoryByPids(['pid' => 0],'id, name');
        }
        $category = array_column($category, 'name', 'id');
        $categoryIds = array_keys($category);

        // 获取二级分类
        $secondCategory = (new CategoryModel())->getChildCategoryByPids(['pid' => $categoryIds]);
        $pidCategory = [];
        foreach ($secondCategory as $key => $item) {
            $pidCategory[$item['pid']][] = $item;
        }

        $result = [];
        foreach ($categoryIds as $k => $categoryId) {
            $result[$k]['categorys']['name'] = $category[$categoryId];
            $result[$k]['categorys']['list'] = (array)$pidCategory[$categoryId];
        }
        // 获取商品
        foreach ($categoryIds as $k => $categoryId) {
            $result[$k]['goods'] = $this->getNormalGoodsFindInSetCategoryId($categoryId);
        }
        return $result;
    }

    /**
     * 按categoryId获取数据
     * @param $categoryId
     * @return array
     */
    public function getNormalGoodsFindInSetCategoryId($categoryId) {
        $field = 'sku_id as id, title, price , recommend_image as image';
        try {
            $result = $this->model->getNormalGoodsFindInSetCategoryId($categoryId, $field);
        } catch (\Exception $e) {
            return [];
        }
        return $result->toArray();
    }

    public function getNormalLists($data, $num, $order) {
        try {
            $field = 'sku_id as id, title, recommend_image as image,price';
            $list = $this->model->getNormalLists($data, $num, $field, $order);
            $res = $list->toArray();
            $result = [
                'total_page_num' => isset($res['last_page']) ? $res['last_page'] : 0,
                'count'          => isset($res['total']) ? $res['total'] : 0,
                'page'           => isset($res['current_page']) ? $res['current_page'] : 0,
                'page_size'      => $num,
                'list'           => isset($res['data']) ? $res['data'] : []
            ];
        } catch (\Exception $e) {
            ///echo $e->getMessage();exit;
            $result = [];
        }
        return $result;
    }

    /**
     * 获取商品详情
     * @param $skuId
     * @return array
     */
    public function getGoodsDetailBySkuId($skuId) {
        // sku_id sku表 => goods_id goods表 => title image description
        // sku  => sku数据
        // join
        $skuBisObj = new GoodsSkuBis();
        $goodsSku = $skuBisObj->getNormalSkuAndGoods($skuId);
        if (!$goodsSku) {
            return [];
        }
        if (empty($goodsSku['goods'])) {
            return [];
        }

        $goods = $goodsSku['goods'];
        // 获取sku数据
        $skus = $skuBisObj->getSkusByGoodsId($goods['id']);
        if (!$skus) {
            return [];
        }
        $flagValue = '';
        foreach ($skus as $sv) {
            if ($sv['id'] == $skuId) {
                $flagValue = $sv['specs_value_ids'];
            }
        }
        $gids = array_column($skus, 'id', 'specs_value_ids');

        if ($goods['goods_specs_type'] == 1) {
            $sku = [];
        } else {
            $sku = (new SpecsValueBis())->dealGoodsSkus($gids, $flagValue);
        }

        $domain = $_SERVER['REQUEST_SCHEME'] . '://' . $_SERVER['HTTP_HOST'];
        $result = [
            'title'       => $goods['title'],
            'price'       => $goodsSku['price'],
            'cost_price'  => $goodsSku['cost_price'],
            'sales_count' => 0,
            'stock'       => $goodsSku['stock'],
            'gids'        => $gids,
            'image'       => $goods['carousel_image'],
            'sku'         => $sku,
            'detail'      => [
                'd1' => [
                    '商品编码' => $goodsSku['id'],
                    '上架时间' => $goods['create_time'],
                ],
                'd2' => preg_replace('/(<img.+?src=")(.*?)/', '$1' . $domain . '$2', $goods['description']),
            ],
        ];

        // 记录数据到redis 作为商品PV统计
        Cache::inc('mall_pv_' . $goods['id']);
        return $result;
    }

    /**
     * 更新库存
     * @param $data
     * @return bool
     */
    public function updateStock($data)
    {
        // 实际上 这个地方 是有性能瓶颈
        // 10 sku_id stock  1 => 10 2= > 4  2 1  1 =>   9 3
        // TODO 批量更新，组装数据saveAll
        foreach ($data as $value) {
            $this->model->decStock($value['goods_id'], $value['num']);
        }
        return true;
    }
}